package com.iwdnb.gkgz.application.service.impl;

import java.util.List;

import com.iwdnb.bmnf.common.utils.BeanConvertUtils;
import com.iwdnb.gkgz.application.service.StockPoolService;
import com.iwdnb.gkgz.common.model.dto.Stock;
import com.iwdnb.gkgz.application.vo.StockConstants;
import com.iwdnb.gkgz.infrastructure.dao.entity.StockPoolDO;
import com.iwdnb.gkgz.infrastructure.dao.repo.StockPoolRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * 默认国内
 *
 * @author pengl
 * @date 2020/11/9
 */
@Component
public class StockPoolServiceImpl implements StockPoolService {
    private static final Logger logger = LoggerFactory.getLogger(StockPoolServiceImpl.class);

    @Autowired
    StockPoolRepository repository;

    @Autowired
    TaskExecutor taskExecutor;


    @Cacheable(value = StockConstants.KEY_STOCK_POOL_LIST, unless= "#result.size() == 0")
    @Override
    public List<Stock> getStockList() {
        List<StockPoolDO> poolDOS = repository.findAll();
        return BeanConvertUtils.convertList(poolDOS, Stock.class);
    }

    @Caching(
            put = {@CachePut(value = StockConstants.KEY_STOCK_POOL, key = "#stock.code")},
            evict = {@CacheEvict(value = StockConstants.KEY_STOCK_POOL_LIST, allEntries = true)}
    )
    @Override
    @Transactional
    public Stock addStock(Stock stock) {
        logger.info("addStock:{}",stock.getCode());
        StockPoolDO queryStock = repository.findByCode(stock.getCode());

        StockPoolDO poolDO = BeanConvertUtils.convert(stock, StockPoolDO.class);
        if(queryStock != null){
            poolDO.setId(queryStock.getId());
        }
        repository.save(poolDO);

        return stock;
    }

    @Cacheable(value = StockConstants.KEY_STOCK_POOL, key = "#code", unless="#result == null")
    @Override
    public Stock findByCode(String code) {
        logger.info("findByCode:{}",code);
        StockPoolDO poolDO = repository.findByCode(code);
        Stock stock = BeanConvertUtils.convert(poolDO, Stock.class);
        return stock;
    }

    @Caching(evict = {
                    @CacheEvict(value = StockConstants.KEY_STOCK_POOL, key = "#stock.code"),
                    @CacheEvict(value = StockConstants.KEY_STOCK_POOL_LIST, allEntries = true)
            })
    @Override
    @Transactional
    public void removeStock(Stock stock) {
        logger.info("removeStock:{}",stock.getCode());
        repository.deleteByCode(stock.getCode());
    }
}
